/*
	$Id: checklist.js,v 1.14 2011-03-15 07:07:16 eike Exp $
	Thanks to Martin and Pete from Team Spockholm. I have learned and stolen a lot from their bookmarklets, and thanks for hosting this on their page.
	You're doing a great job! Spock on!
	Also many thanks for Jennifer, the Mafia Wars Loot Lady (http://mwlootlady.blogspot.com/) for testing, proposing cool things and writing an excellent article about this bmlet.	
	All other credits go to Google. Everything about javascript (everything about everything) is right at your fingertips.
*/
/*
	History/TODO:
	1.01
			(v)sorting the list
			(v)optional sorting
			(v)moving the list
			(v)lots of new items  
			(v)can use link even when inactive
	1.02
		  	(v) timer for informant podcast
			(v) tournament-o-matic 
			(v) property
			(v) item update
	1.03
			(v) server
	1.04
			    minor update, don't remember
	1.05
			(v) superserver
			(v) improved dragging code from JQuery.UI.draggable (great!!)
	1.06
			(v) Added MWid to cookie name.
			(v) scrollable
	1.07
			(v) Timer to minutes instead of seconds
			(v) reload problem (dead icon in mafia wars logo)
			
	1.08
			(v) Energy Pack timer back to 23h
	1.09		
			(v) Slotmachine added
	1.10
			(v) Daily Statpoint
			(v) new unframe code
			
	1.x
			(x) configuration menu instead of icons
			...
*/
javascript:(function (){
var server=false;
var version='Checklist v1.10'+(server?' server':'');
var debug=false;
try {
	if (navigator.appName == 'Microsoft Internet Explorer') {
		alert('You are using Internet Explorer, this bookmarklet will not work.\nUse Firefox or Chrome instead.');
		return;
	}
	if (/m.mafiawars.com/.test(document.location)) {
		window.location.href = document.location+'?iframe=1';
	}
	else if (/apps.facebook.com.inthemafia/.test(document.location)) {
		//Credits to Christopher(?) for this new fix
		for (var i = 0; i < document.forms.length; i++) {
			if (/^canvas_iframe_post/.test(document.forms[i].id)) {
				document.forms[i].target = '';
				document.forms[i].submit();
				return;
			}
		}
	}
	else if (document.getElementById('some_mwiframe')) {
		// new mafiawars.com iframe
		window.location.href = document.getElementById('some_mwiframe').src;
		return;
	}
	else {
		document.body.parentNode.style.overflowY = "scroll";
		document.body.style.overflowX = "auto";
		document.body.style.overflowY = "auto";
		try {
			document.evaluate('//div[@id="mw_city_wrapper"]/div', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).style.margin = "auto";
			if (typeof FB != 'undefined') {
				FB.CanvasClient.stopTimerToSizeToContent;
				window.clearInterval(FB.CanvasClient._timer);
				FB.CanvasClient._timer = -1;
			}
			document.getElementById('snapi_zbar').parentNode.parentNode.removeChild(document.getElementById('snapi_zbar').parentNode);

		} catch (fberr) {}
		//Revolving Revolver of Death from Arun, http://arun.keen-computing.co.uk/?page_id=33
		$('#LoadingBackground').hide();
		$('#LoadingOverlay').hide();
		$('#LoadingRefresh').hide();
	}
} catch(mainerr) {
	var spock_div=document.getElementById('spockdiv');
	if(spock_div) {
		spock_div.innerHTML='';
	}
	alert('Some error occured, Friends Stats not loaded.\nDid you run on an unframed MW page?\nIf you did, report the message below (NOT THIS TEXT) to Spockholm:\n\n'+version+'\n'+mainerr);
}

	function log(s){
		if (debug==true){
			document.getElementById('spockletlog').innerHTML+=s+'<br>';
		}
	}
  
	function unix_timestamp() {
		return parseInt(new Date().getTime().toString().substring(0, 10))
	}

	/**
	* from http://binnyva.blogspot.com/2005/10/dump-function-javascript-equivalent-of.html
	* only used for debugging
	* Function : dump()
	* Arguments: The data - array,hash(associative array),object
	*    The level - OPTIONAL
	* Returns  : The textual representation of the array.
	* This function was inspired by the print_r function of PHP.
	* This will accept some data as the argument and return a
	* text that will be a more readable version of the
	* array/hash/object that is given.
	*/
	function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
	 for(var item in arr) {
	  var value = arr[item];
	 
	  if(typeof(value) == 'object') { //If it is an array,
	   dumped_text += level_padding + "'" + item + "' ...\n";
	   dumped_text += dump(value,level+1);
	  } else {
	   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	  }
	 }
	} else { //Stings/Chars/Numbers etc.
	 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
	} 
	
	// from Yevgen Silant'yev, http://joyka.pp.ua/
	function getMWURL() {
		str = document.location;
		str = str.toString();
		beg = str.substring(0,str.indexOf('?')+1);
		str = str.substring(str.indexOf('?')+1);
		str = str.split('&');
		mid = '';
		for(var i=0;i<str.length;i++){
			if(str[i].indexOf('sf_xw_')==0){ mid=mid+str[i]+'&'; }
		}
		return beg+mid;
	}
	if (navigator.appName == 'Microsoft Internet Explorer') { 
		alert('You are using Internet Explorer, this bookmarklet will not work.\nUse Firefox or Chrome instead.');
		return;
	}
	// createCookie from Vern's Toolkit http://vern.com/mwtools/
	function createCookie(name,value) {
		// expire one month from now
		var expires = new Date();
		expires.setDate(expires.getDate()+30);
		document.cookie = name+"="+value+";expires="+expires.toGMTString()+"; path=/";
	}

	// readCookie from Vern's Toolkit http://vern.com/mwtools/
	function readCookie(name) {
		var i,
			cookie,
			nameEQ = name+"=",
			cookieArray = document.cookie.split(";");
		for (i=0; i< cookieArray.length; i++) {
			cookie = cookieArray[i];
			while (cookie.charAt(0)==' ')
				cookie = cookie.substring(1,cookie.length);
			if (cookie.indexOf(nameEQ) == 0)
				return cookie.substring(nameEQ.length,cookie.length);
		}
		return null;
	}
	
	
	var MWURL = getMWURL();
	//var sf_xw_sig = /sf_xw_sig=([a-fA-F0-9]+)/.exec(document.body.innerHTML)[1];
	var userid =/sf_xw_user_id': '(.+)'/.exec(document.body.innerHTML)[1];
	var uid= /p\|(\d+)/.exec(userid)[1];
	var personid = /([a-z]\|([0-9]+))/.exec(userid)[2];
	var fb_userid = FB.Facebook.apiClient.get_session().uid+'';
	var run=1,xmlHTTP,content=document.getElementById('final_wrapper');
	mw_url='http://apps.facebook.com/inthemafia/profile.php?id=%7B%22user%22%3A%22ID%22%7D',color='#BCD2EA',
	fb_url='http://www.facebook.com/profile.php?id=';
	var stopimg = '';
	var scrollimg = '';
	var scrollimg2 = '';
	var clockimg = '';
	var spsort=true;
	var spscroll=false;
	var spcookieserver='http://www2.spockholm.com/checklist.php';
	var spserverpassword='';
	var spseconds=false;
	var timeoutid=null;
	
	// config, all possible todolist-items
	// linktype: 1->ingame-url with do_ajax, 2->Spocklet, 3->link in new window, 4->ingame-url with travel, 100+->special
	var config = {
		0: {
		'name':'Daily Take',
		'linktype':101, // special
		'url':'', // determine later
		'update': '',
		'interval':23 // 11pm PST
		},
		1: {
		'name':'Declare War',
		'linktype':1, //url
		'url':'remote/html_server.php?xw_controller=war&xw_action=view',
		'update': 'wartab_text',
		'interval':16+24 // every 16h
		},
		2: {
		'name':'Daily Chance',
		'linktype':1, //link
		//'url':'remote/html_server.php?xw_controller=lotto&xw_action=view',
		'url':'remote/html_server.php?xw_controller=lotto&xw_city=1&xw_action=view&xw_person=68031107&mwzy_token=fbcdd05c3174de6fa3d5fbb36381afec2714c26ed1f928638907c1a16e0587e8',
		//'url':'',
		'update': '',
		'interval':7 // 7am
		},
		3: {
		'name':'Atlantic Bonus',
		'linktype':3, //new window link
		'url':'http://m.mafiawars.com/',
		'update': '',
		'interval':23 // 7am
		},
		4: {
		'name':'E-Mail Bonus',
		'linktype':3,
		'url':'http://www.facebook.com/topic.php?uid=131902633521767&topic=407',
		'update': '',
		'interval':48
		},
		5: {
		'name':'Tournament',
		'linktype':2,
		'url':'http://www.spockholm.com/mafia/tournament-o-matic.js',
		'update': 'tournament_try_again_timer',
		'interval':28
		},
		6: {
		'name':'Get-A-Nator',
		'linktype':2, //spocklet
		'url':'http://www.exellerate.com/mafia/free_gift_get_a_nator.js',
		'update': 'manual',
		'interval':48 // free to choose, default=24h
		},
		7: {
		'name':'Link-A-Nator',
		'linktype':2, //spocklet
		'url':'http://www.exellerate.com/mafia/link-a-nator.js',
		'update': 'manual',
		'interval':48 // free to choose, default=24h
		},
		8: {
		'name':'Search Ops/Wars',
		'linktype':2, //spocklet
		'url':'http://www.spockholm.com/mafia/mission-war-hunter.js',
		'update': 'manual',
		'interval':32 // free to choose, default=24h
		},
		9: {
		'name':'Build NY',
		'linktype':2, //spocklet
		'url':'http://www.exellerate.com/mafia/crafty_lil_helper_beta.js',
		'update': 'bcm_timer_countdown',
		'interval':42 // 18
		},
		10: {
		'name':'Free Slots',
		'linktype':102, //spocklet
		'url':'',
		'update': '',
		'interval':48
		},
		11: {
		'name':'Build Italy',
		'linktype':4, //link with travel
		'url':'remote/html_server.php?xw_controller=propertyV2&xw_action=view&xw_city=6',
		'update': '',
		'interval':47
		},
		12: {
		'name':'Energy Pack',
		'linktype':104, //special
		'url':'',
		'update': 'empire_energy_time_left',
		'interval':47
		},
		13: {
		'name':'MiniPack',
		'linktype':2, //spocklet
		'url':'http://www.spockholm.com/mafia/minipack.js',
		'update': '',
		'interval':32
		},
		14: {
		'name':"Fighter's Energy Refill",
		'linktype':103,  // fightclub marketplace
		'url':'',
		'update': 'fm_timer_full_1',
		'interval':42
		},
		15: {
		'name':'removed',
		'linktype':103,
		'url':'',
		'update': '',
		'interval':-1
		},
		/***************** new 1.01 ********************/
		16: {
		'name':'Bagman Mugger',
		'linktype':2,
		'url':'http://www.exellerate.com/mafia/mystery_bagger.js',
		'update': 'manual',
		'interval':48 // only every 7 days
		},
		17: {
		'name':'Loose slots',
		'linktype':2,
		'url':'http://www.exellerate.com/mafia/loose_slots.js',
		'update': '',
		'interval':48 // only every 7 days
		},
		18: {
		'name':'Stream Helper',
		'linktype':2,
		'url':'http://www.spockholm.com/mafia/stream-helper.js',
		'update': 'manual',
		'interval':48 // only every 7 days
		},
		19: {
		'name':'Accept Gifts',
		'linktype':3,
		'url':'http://www.facebook.com/reqs.php',
		'update': '',
		'interval':23
		},
		20: {
		'name':'Job/Parts help',
		'linktype':2,
		'url':'http://codeoutpost.com/Scripts/FeedHelper.js',
		'update': 'manual',
		'interval':48 // only every 7 days
		},
		21: {
		'name':'Crime Spree',
		'linktype':105, // ZMC
		'url':'',
		'update': '',
		'interval':48 // only every 7 days
		},
		22: {
		'name':'The Informant Podcast',
		'linktype':106,
		'url':'', // generated automagically
		'update': '',
		'interval':-100
		},
		23: {
		'name':'Crew collections',
		'linktype':1,
		'url':'remote/html_server.php?xw_controller=collection&xw_action=view&filter_col=4',
		'update': 'soc_col_timer_4',
		'interval':72
		},
		24: {
		'name':'Collect properties',
		'linktype':2,
		'url':'http://www.spockholm.com/mafia/property_collector.js',
		'update': 'manual',
		'interval':48
		},
/*                25: {
                'name':'Collect fans',
                'linktype':2,
                'url':'http://www.spocklet.com/bookmarklet/soccerfan-beta.js',
                'update': '',
                'interval':42
		},*/
		25: {
		'name':'Slotmachine',
		'linktype':2,
		'url':'http://slotmachine.spocklet.com/slots.js',
		'update': '',
		'interval':48
		},
		26: {
		'name':'Daily Skillpoint',
		'linktype':3,
		'url':'http://www.facebook.com/MafiaWarsFans?sk=wall',
		'update': '',
		'interval':0
		}
		};

	configlength=27;

	var tip_lastepisode_link='', tip_time=0, tip_string='', tip_lastcheck=0;
	
  
	
	// individual status, will be saved in a cookie
	var status=new Object();
	/*
		return seconds until event is ready, or zero if it is ready
	*/
	function getTimeUntil(i, ts){
		t=unix_timestamp();
		if (i>24) {
			i-=24;
			if ((t-ts)>(i*3600)){
				return 0;
			} else {
				return (i*3600)-(t-ts);
			}
		} else if (i==-100) {
			if(ts<tip_time) {
				return 0;
			} else {
				// time to next episode
				// use t and calculate next
				now=new Date(); 
				now.setTime(now.getTime()+((now.getTimezoneOffset()/60)-6)*3600000); // now in CST	
				wday=now.getDay();
				if (wday==0)  {days=1; }
				if (wday==6)  {days=2; }
				if (wday==2)  {days=3; }
				if (wday==3)  {days=2; }
				if (wday==4)  {days=1; }
				
				if ((wday==1)||(wday==5))  {
				   tip_string='today!'
				} else {
					tip_string='in '+days+' days!'
				}
				return 86400*7; 
			}
		} else {
			var last=new Date();
			var next=new Date();
			i=(i-last.getTimezoneOffset()/60+8) % 24; // t in local time
			last.setHours(i); last.setMinutes(0); last.setSeconds(0); last.setMilliseconds(0);
			next.setHours(i); next.setMinutes(0); next.setSeconds(0); next.setMilliseconds(0);
			
			if ((next.getTime()/1000)<t) {
				// event already passed today, set next to tomorrow
				next.setTime(next.getTime()+86400000);
			} else {
				// event not yet passed today, set last to yesterday
				last.setTime(last.getTime()-86400000);
			}

			if (ts<(last.getTime()/1000)) {
				return 0;
			} else {
				return (next.getTime()/1000)-t;
			}
		}
	}
	/*
		read status hash from cookie, deserialize and save in status
	*/
	function getStatus(){
		var cook=readCookie(uid+'_spocklet_todo_status');
		// if server -> fetch from server
		if (cook==null) { 
			// try without uid
			var cook=readCookie('spocklet_todo_status');
			if (cook==null) { cook=''; }
		}
		var stats=cook.split('|');
		var last, interval;
		for(var i=0;i<configlength;i++){
			try {
				sts=stats[i].split('#');
				last=sts[1];
				interval=sts[2];
				if (last==undefined) { last=1; }
				if (interval==undefined) { interval=config[i]['interval']; }
			} catch(err) {
				last=0;
				interval=(config[i]['update']=='manual')?48:-1; // if not set and value is -1, set to 24h
			}
			try {
				status[i]['last']=last
				status[i]['interval']=interval;
			} catch(err) {
				status[i]=new Object();
				status[i]['last']=last
				status[i]['interval']=interval;
			}
		}
//		setStatus(); // save in case something was missing or it was invalid
	} 
	/*
		serialize status and save in cookie
	*/
	function setStatus(){
		var cook='';
		for(i=0;i<configlength;i++){
			try {
				cook+=i+'#'+status[i]['last']+'#'+status[i]['interval']+'|';
			} catch(err) {
				cook+=i+'#100#-1|';
			}
		}
		createCookie(uid+'_spocklet_todo_status',cook);
		if (server) {
			saveServer(cook);
		}
	}
	
	/*
		load from server / only for server mode
	*/
	function loadServer() {
		if (server) { // yes, double check!
			if (!spserverpassword) {
				try {
					spserverpassword=readCookie(uid+'_spserverpassword');
				} catch(e) {
				}
				if (!spserverpassword) {
					spserverpassword=prompt("Please enter your password:","");
					createCookie(uid+'_spserverpassword',spserverpassword);
				}
			}
			$.ajax({
				url:spcookieserver+'?r='+Math.random()+'&action=read&id='+fb_userid+'&pass='+escape(spserverpassword)+'',
				dataType: "jsonp",
				success: function(data) {
					if (data.status=='readok') {
						createCookie(uid+'_spocklet_todo_status',data.cookie);
						display();
					} else if (data.status=='authfail') {
						if (confirm('Wrong password, do you want to go the application page to see your password?')) {
							window.open('http://apps.facebook.com/mafiachecklist/','_blank');
						}
						spserverpassword=prompt("Please re-enter:\nLeave empty to exit.","");
						if (spserverpassword) { 
							createCookie(uid+'_spserverpassword',spserverpassword);
							loadServer();
						}
					} else {
						alert('Other error.');
					}
			}});
		}
	}
	
	function saveServer(cook) {	
		if (server) { // yes, double check!
			$.ajax({
				url:spcookieserver+'?r='+Math.random()+'&action=write&id='+fb_userid+'&pass='+escape(spserverpassword)+'&cookie='+escape(cook),
 				dataType: "jsonp",
				success: function(data) {
					if (data.status=='writeok') {
						// ok
					} else if (data.status=='authfail') {
						spserverpassword=prompt("Wrong password, please re-enter:\nLeave empty to exit.","");
						if (spserverpassword) { 
							createCookie(uid+'_spserverpassword',spserverpassword);
							saveServer();
						}
					} else {
						alert('Other error.');
					}			
				}});
			
		}			
	}

	/*
		reset all
	*/
	function resetStatus(){
		for(var i=0;i<configlength;i++){
			status[i]['last']=0;
			status[i]['interval']=0;
		}
		setStatus();
		display();
	}
	/*
		re-add all
	*/
	function readdStatus(){
		for(var i=0;i<configlength;i++){
			if (status[i]['last']==-1) {
				status[i]['last']=0;
			}
		}
		setStatus();
		display();
	}
	/*
		remove cookie
	*/
	function removeCookie(){
		status=new Object();
		createCookie(uid+'_spocklet_todo_status','');
		getStatus();
		display();
	}

	// running html, only the spocklettodo will be filled in display()
	var running_html = ''+
	'	<style type="text/css">'+
	'		#sp_fullview { '+
	'			display: inline;'+
	'			position: fixed;'+
	'			max-width: 250px;'+
	'			top: 0px; left: 0px;'+
	'			z-index: 100;'+
	'			border: 1px solid #FFF;'+
	'			background-color: #000;'+
	'			margin:3px;'+
	'		}'+
	'		#sp_smallview { '+
	'			display: inline;'+
	'			position: absolute;'+
	'			height: 43px;'+
	'			right: 395px;'+
	'			top: 8px;'+
	'			width: 43px;'+
	'			z-index: 3;'+
	//'			border: 1px solid #FFF;'+
	//'			background-color: #aaa;'+
	//'			opacity: 0;'+
	'			cursor: pointer;'+
	'		}'+
	'		img {'+
	'		border:0px;}'+
	'		#spdrag::-moz-selection           { background-color: black; color: white; }'+
	'		#spdrag::selection                { background-color: black; color: white; }'+
	'</style>'+
	'<table id="sp_fullview" border=0>'+
	'<tr>'+
	'	<td style="text-align:left;font-size:0.8em;" ><a id="sphelp" href="#"><img src="http://mwfb.static.zgncdn.com/mwfb/graphics/icon-help.gif"></a> <a id="spsort" href="#"><img title="list will be sorted" src="http://mwfb.static.zgncdn.com/mwfb/graphics/inventory/ItemCard/icons/Inventory-active-icon.png"></a> <a title="toggle minutes/seconds" id="spclock" href="#"><img src="'+clockimg+'"></a></td>'+
	'	<td style="text-align:center; color:#FFFFFF; width=100%"><b id="spdrag" style="cursor:move; font-size:16px;">Checklist</b> <small style="font-size:11px"><a id="sphide" href="#">hide</a></small></td>'+
	'	<td style="text-align:right;font-size:0.8em;" ><a id="spscroll" href="#"><img src="'+scrollimg+'"></a> <a id="spclose" href="#"><img src="'+stopimg+'"></a></nobr></td>'+
	'</tr>'+
	'<tr>'+
	'	<td colspan="3">'+
	'	<span id="spocklettodo">'+
	'	</span>'+
	'	</td>'+
	'</tr>'+
	'<tr>'+
	'	<td colspan="3"><span id="spockletlog"></span></td>'+
	'</tr>'+
	'<tr>'+
	'	<td colspan="3" style="font-size:0.8em;">'+
	'	<a href="http://www.spockholm.com/mafia/bookmarklets.php" target="_top">'+version+' by Team Spockholm</a><br>'+
	'	<a href="#" id="spremovecookie">remove cookie</a> / <a href="#" id="spreadd">add all removed</a> / '+
	'	<a href="http://spockholm.userecho.com/" target="_blank">add items</a><br>'+
	'	<a href="http://www.spockholm.com/mafia/donate.php?Checklist" alt="Buy me a beer" target="_blank">PintWare</a> - <a href="http://bit.ly/saveclickmonkeys" target="_blank">Save the Clickmonkey</a>'+
	'	</td></tr>'+
	'</tr>'+
	'</table>';
	
	var small_html = ''+
	'<table id="sp_smallview"><tr><td style="-moz-border-radius: 5px; border: 1px #FFF;width:40px; height: 40px;">'+
	'<a id="spshow" href="#"><img style="position: absolute; left:12px; top:7px;" src="http://mwfb.static.zgncdn.com/mwfb/graphics/flags/mw_messagebox_checkbox1_normalized.gif">'+
	'<span id="sp_overview" style="position: absolute; left:10px; top:25px; width:25px; height: 16px; color: rgb(255, 255, 255); font-weight: bold; text-align: center; background-image: url(http://mwfb.static.zgncdn.com/mwfb/graphics/zmc/fb_pill_25x16_01.png); background-attachment: initial; background-origin: initial; background-clip: initial; background-color: initial; display: block; background-position: 50% 50%; background-repeat: no-repeat no-repeat; "></span></a>'+
	'</td></tr></table>'+
	'';
	
	
	/*
		hang in document structure
	*/
	function create_div() {
		if(document.getElementById('spocklet_todo_div')) {
			document.getElementById('spocklet_todo_div').innerHTML = running_html;
		}
		else {
			var spock_div=document.createElement("div");
			spock_div.id = 'spocklet_todo_div';
			spock_div.innerHTML = running_html;
			content.appendChild(spock_div);
		}
		if (document.getElementById('sp_smallicon')) {
		    document.getElementById('sp_smallicon').innerHTML = small_html;
		} else {
			var toolbar=document.getElementById('mw_masthead');
			var smallicon=document.createElement("div");
			smallicon.id = 'sp_smallicon';
			smallicon.innerHTML = small_html;
			toolbar.appendChild(smallicon);
		}
	}
	create_div();

	/*
		close function
	*/
	document.getElementById('spclose').onclick=function(e) {
		run = 0;
		document.getElementById("final_wrapper").removeChild(document.getElementById("spocklet_todo_div"));
		document.getElementById("mw_masthead").removeChild(document.getElementById("sp_smallicon"));
		return false;
	};
 	document.getElementById('spreadd').onclick=function(e) {
		readdStatus();
		return false;
	};
	document.getElementById('spremovecookie').onclick=function(e) {
		removeCookie();
		return false;
	};
	
	document.getElementById('sphide').onclick=function(e) {
		//document.getElementById('sp_smallview').style.display='inline';
		document.getElementById('sp_fullview').style.display='none';
		return false;
	};
	document.getElementById('spshow').onclick=function(e) {
		//document.getElementById('sp_smallview').style.display='none';
		if (document.getElementById('sp_fullview').style.display=='none') {
			document.getElementById('sp_fullview').style.display='inline';
		} else {
			document.getElementById('sp_fullview').style.display='none';
		}
		return false;
	};
	document.getElementById('sphelp').onclick=function(e) {
		window.open('http://mwlootlady.blogspot.com/2011/01/checklist-update.html');
		return false;
	};
	document.getElementById('spsort').onclick=function(e) {
		var button=document.getElementById('spsort');
		if (spsort) {
			button.innerHTML='<img title="list is not sorted" src="http://mwfb.static.zgncdn.com/mwfb/graphics/inventory/ItemCard/icons/Inventory-inactive-icon.png">';
			spsort=false;
		} else {
			button.innerHTML='<img title="list will be sorted" src="http://mwfb.static.zgncdn.com/mwfb/graphics/inventory/ItemCard/icons/Inventory-active-icon.png">';
			spsort=true;
		}
		return false;
	}
	document.getElementById('spscroll').onclick=function(e) {
		var button=document.getElementById('spscroll');
		if (!spscroll) {
			document.getElementById('sp_fullview').style.height='100%';
			document.getElementById('sp_fullview').style.overflow='scroll';
			button.innerHTML='<img title="add scrollbars" src="'+scrollimg2+'">';
			button.blur();
			spscroll=true;
		} else {
			document.getElementById('sp_fullview').style.height='auto';
			document.getElementById('sp_fullview').style.overflow='auto';
			button.innerHTML='<img title="remove scrollbars" src="'+scrollimg+'">';
			button.blur();
			spscroll=false;
		}
		return false;
	}	
	document.getElementById('spclock').onclick=function(e) {
		spseconds=!spseconds;
		display();
		if(timeoutid) {
			clearTimeout(timeoutid);
		} 
		if (spseconds) {
			timeoutid=setTimeout(start, 1000);
		} else {
			timeoutid=setTimeout(start, 15000);
		}
	}
	
/*
	// drag drop code, thanks selfhtml
	var dragobjekt = null;
	var dragx = 0;
	var dragy = 0;
	var posx = 0;
	var posy = 0;

	function dragmove(ereignis) {
	  posx = document.all ? window.event.clientX : ereignis.pageX;
	  posy = document.all ? window.event.clientY : ereignis.pageY;
	  if(dragobjekt != null) {
		dragobjekt.style.left = (posx - dragx) + "px";
		dragobjekt.style.top = (posy - dragy) + "px";
	  }
	};
	document.onmousemove=dragmove;
	
	function dragstart(element) {
		document.onmousemove=dragmove;
		dragobjekt = element;
		dragx = posx - dragobjekt.offsetLeft;
		dragy = posy - dragobjekt.offsetTop;
	  }

	  document.getElementById("spdrag").onmousedown=function(e){
		dragstart(document.getElementById("sp_fullview"));
	}
	document.onmouseup=function(e){
		dragobjekt=null;
		document.onmousemove=null;
	}
*/
	$("#sp_fullview").draggable({ handle: "b" });
	$("#sp_fullview").disableSelection();
	//$("#sp_fullview").resizable();
	
	
	function readyIn(i,interval){
		if (interval>-2) {
			var tt,h,m,s;
			h=Math.floor(i/3600);
			i-=h*3600;
			m=Math.floor(i/60);
			s=i-m*60;
			if (spseconds) {
				tt=(h<10?'0':'')+h+':'+(m<10?'0':'')+m+':'+(s<10?'0':'')+s;
			} else {
				tt=(h<10?'0':'')+h+':'+(m<10?'0':'')+m;
			}
			return '<span class="more_in">'+tt+'</span>';
		} else if (interval==-100) {
			if ((unix_timestamp()-tip_lastcheck)>3600) { // refresh every hour
				tip_lastcheck=unix_timestamp();
				
			  $.ajax({
					url:'http://informantpodcast.com/informant-release.php?callback=calleikeback',
					dataType: "jsonp",
					success: function(data) {
						tip_lastepisode_link=data.link;
						tip_string='~3 days';
						
						tip_time=data.timestamp;
						
						
				}});			
				return '<span class="more_in" id="spipodcast">updating...</span>';
			} else {
				return '<span class="more_in" id="spipodcast">'+tip_string+'</span>';
				
			
			}
			
		}
	}
	
	function ex_me(i){
		getStatus();
		status[i]['last']=-1;
		setStatus();
		display();
	}

	function did_me(i) {
		getStatus();
		status[i]['last']=unix_timestamp();
		setStatus();
		display();
	}
	function undid_me(i) {
		getStatus();
		status[i]['last']=unix_timestamp()-864000;
		setStatus();
		display();
	}
	function change_setting(i,t) {
		getStatus();
		status[i]['interval']=parseInt(t)+24;
		setStatus();
		display();
	}
	
	/*
		Either get automatic update on items that is on the page, or let the user select the time
	*/
	function update(i,event){
		if (config[i]['update']!='') {
			if (config[i]['update']=='manual') {
				var element=document.getElementById('spocklet_todo_div');
				var popup=document.createElement("div");
				popup.id = 'sp_popup';
				var popup_html=''+
					'<div style="position:fixed; z-index:101; border: 1px solid white; background:#333; left: '+event.pageX+'px; top:'+event.pageY+'px;">'+
					'<table><tr>'+
					'<td colspan=3 style="text-align:center;">Select your interval</td>'+
					'</tr><tr>'+
					'<td style="text-align:center;"><a class="sp_set" id="sp_set'+i+'_1" href="#">1h</a></td>'+
					'<td style="text-align:center;"><a class="sp_set" id="sp_set'+i+'_2" href="#">2h</a></td>'+
					'<td style="text-align:center;"><a class="sp_set" id="sp_set'+i+'_4" href="#">4h</a></td>'+
					'</tr><tr>'+
					'<td style="text-align:center;"><a class="sp_set" id="sp_set'+i+'_8" href="#">8h</a></td>'+
					'<td style="text-align:center;"><a class="sp_set" id="sp_set'+i+'_12" href="#">12h</a></td>'+
					'<td style="text-align:center;"><a class="sp_set" id="sp_set'+i+'_16" href="#">16h</a></td>'+
					'</tr><tr>'+
					'<td style="text-align:center;"><a class="sp_set" id="sp_set'+i+'_24" href="#">1d</a></td>'+
					'<td style="text-align:center;"><a class="sp_set" id="sp_set'+i+'_48" href="#">2d</a></td>'+
					'<td style="text-align:center;"><a class="sp_set" id="sp_set'+i+'_168" href="#">7d</a></td>'+
					'</tr><tr><td colspan=3 style="text-align:center;"><a href="#" onclick="javascript: document.getElementById(\'sp_popup\').parentNode.removeChild(document.getElementById(\'sp_popup\')); return false;">close</a></td></tr></table>'+
					'</div>'+
					'';
				
				popup.innerHTML = popup_html; 
				element.appendChild(popup);
        // popup
				var as=document.getElementsByClassName('sp_set');
				for(var i=0;i<as.length;i++){
					if (as[i]){
						as[i].onclick=function(e){
							if (m=/sp_set(\d+)_(\d+)$/.exec(this.id)) {
								change_setting(m[1],m[2]);
							}
							document.getElementById('sp_popup').parentNode.removeChild(document.getElementById('sp_popup'));
							return false;
						};
					}
				}

			} else {
				if (config[i]['update']!='') {
					if (el=document.getElementById(config[i]['update'])) {
						var element=document.getElementById('spocklet_todo_div');
						var popup=document.createElement("div");
						popup.id = 'sp_popup';
						var popup_html=''+
							'<div style="position:fixed; z-index:101; border: 1px solid white; background:#333; left: '+event.pageX+'px; top:'+event.pageY+'px;">'+
							'<table><tr>'+
							'<td colspan=3 style="text-align:center;"><a id="sp_set'+i+'" href="#">set to '+el.innerHTML+'</a></td>'+
							'</tr><tr><td colspan=3 style="text-align:center;"><a href="#" onclick="javascript: document.getElementById(\'sp_popup\').parentNode.removeChild(document.getElementById(\'sp_popup\')); return false;">close</a></td></tr></table>'+
							'</div>'+
							'';
						
						popup.innerHTML = popup_html; 
						element.appendChild(popup);
		        // popup
						var a=document.getElementById('sp_set'+i);
						a.onclick=function(e){
							if (m=/sp_set(\d+)$/.exec(this.id)) {
								var i=m[1];
								
								el=document.getElementById(config[i]['update']);
								if (m=/(\d+)\:(\d+)\:(\d+)\:(\d+)/.exec(el.innerHTML)) {
									status[i]['last']=unix_timestamp()-((config[i]['interval']-24)*3600)+parseInt(m[1])*86400+parseInt(m[2])*3600+parseInt(m[3])*60+parseInt(m[4]); // only fight club
									setStatus();
									display();
								} else if (m=/(\d+)\:(\d+)\:(\d+)/.exec(el.innerHTML)) {
									status[i]['last']=unix_timestamp()-((config[i]['interval']-24)*3600)+parseInt(m[1])*3600+parseInt(m[2])*60+parseInt(m[3]);
									setStatus();
									display();
								} else if (m=/(\d+)\:(\d+)/.exec(el.innerHTML)) {
									status[i]['last']=unix_timestamp()-((config[i]['interval']-24)*3600)+parseInt(m[1])*60+parseInt(m[2]);
									setStatus();
									display();
								}
							}
							document.getElementById('sp_popup').parentNode.removeChild(document.getElementById('sp_popup'));
							return false;
						};
					}
				}
			}
		}
	}
	
	/*
		run the link that take you to the task
	*/
	function go_now(i) {
		// type of link
		url=config[i]['url'];
		if (config[i]['linktype']==1) {
			// link
			do_ajax('inner_page',url,1,1,0,0);
		} else if (config[i]['linktype']==2) {
			// spocklet
			var a=document.createElement("script");
			a.type="text/javascript";
			a.src=url+"?"+Math.random();
			document.getElementsByTagName("head")[0].appendChild(a);
		} else if (config[i]['linktype']==3) {
			// new window
			window.open(url);
		} else if (config[i]['linktype']==4) {
			// ajax with travel
			var cb = userid+unix_timestamp();
			if (m=/xw_city\=(\d+)/.exec(url)) {
				destination=m[1];
			} else { 
				destination=2;
			}
			var params = {
				'destination': destination,
				'from': 'hospital',
				'tmp': '',
				'cb': cb,
				'xw_person': personid,			
				'xw_client_id': 8,
				'ajax': 1, 
				'liteload': 1,
				'sf_xw_sig': local_xw_sig,
				'sf_xw_user_id': userid
			};
			$.ajax({
				type: 'POST',
				data: params,
				url: 'http://facebook.mafiawars.com/mwfb/remote/html_server.php?xw_controller=travel&xw_action=travel',
				success: function(response) {
					try {
						active_city = parseInt(/current_city_id.*?(\d+)/.exec(response)[1]);
						do_ajax('inner_page',url,1,1,0,0);

						return;
					}
					catch (err) { 
					}
				}
			});
		} else if (config[i]['linktype']==101) {
			// daily take
			$('#social_module_daily_take_div').fadeOut(); 
			do_ajax('popup_fodder','remote/html_server.php?xw_controller=DailyChecklist&xw_action=showDailyTake&xw_city=5',1,1);
		} else if (config[i]['linktype']==102) {
			// free slots
			link='http://apps.facebook.com/inthemafia/track.php?next_controller=index&next_action=view&zy_track=feed&sendkey=a&ztrack_category=win_slot&next_params={%22playslots%22:%221%22,%22fromminifeed%22:%221%22,%22wins%22:%222%22,%22user_id%22:%22p|0%22}'
			window.open(link);
			window.open(link);
			do_ajax('popup_fodder','remote/html_server.php?xw_controller=slotmachine&xw_action=view&xw_city=5',1,0);
		} else if (config[i]['linktype']==103) {
			// fighter energy refill
			do_ajax('inner_page', 'remote/html_server.php?xw_controller=marketplace&xw_action=view&xw_city=4&xw_person=95497006&category=8', 1, 0)			
		} else if (config[i]['linktype']==104) {
			// Energy pack
			EnergyPackModule.use();		
		} else if (config[i]['linktype']==105) {
			// ZMC
			do_ajax('popup_fodder', 'remote/html_server.php?xw_controller=messageCenter&xw_action=view&xw_city=5', 1, 1, 0, 0);
		} else if (config[i]['linktype']==106) {
			// TIP
			window.open(tip_lastepisode_link);
		}
		return false;
	}


	
	
	/*
		go through status and config and display all selected items
	*/
	function display(){
		var out=document.getElementById('spocklettodo');
		var t='<table>';
		var open=0;
		getStatus();
		var iarr=new Array();
		// calculate "next" times
		for(var i=0;i<configlength;i++){
			if ((config[i]['update'])=='manual') {
				status[i]['next']=getTimeUntil(status[i]['interval'],status[i]['last']);
			} else {
				status[i]['next']=getTimeUntil(config[i]['interval'],status[i]['last']);
			}
		}
		
		
		for(var i=0;i<configlength;i++){ iarr.push(i); }

		// sort if sort is selected
		if (spsort) {
			iarr.sort(function(a,b){
				if (status[a]['next']>status[b]['next']) {
					return 1;
				} else if (status[a]['next']<status[b]['next']) {
					return -1;
				} else {
					return (a-b);
				}
			});
		}
	
		for(var j=0;j<iarr.length;j++){
			var i=iarr[j];
			tick="<a id='spuntick"+i+"' href='#'><img src='http://mwfb.static.zgncdn.com/mwfb/graphics/flags/mw_messagebox_checkbox1_normalized.gif'></a>";
			notick="<a id='sptick"+i+"' href='#'><img src='http://mwfb.static.zgncdn.com/mwfb/graphics/flags/mw_messagebox_checkbox2_normalized.gif'></a>";
			ex="<a id='spremove"+i+"' href='#'><img src='http://mwfb.static.zgncdn.com/mwfb/graphics/empire/icon_X_close_small.png'></a>";
			
			if (((config[i]['update'])=='manual') || document.getElementById(config[i]['update'])) {
				up="<a id='spupdate"+i+"' href='#'><img src='http://mwfb.static.zgncdn.com/mwfb/graphics/action_box_icon_refresh.gif' height='8' width='8'></a>";
			} else {
				up='';
			}
			
			if(config[i]['linktype']!=0) {
				gonow="<a id='spgonow"+i+"'><nobr>Do it<img src='http://mwfb.static.zgncdn.com/mwfb/graphics/empire/arrow_11px.gif'>&nbsp;</nobr></a>";
				gonow2="<a id='spgonow"+i+"'><img src='http://mwfb.static.zgncdn.com/mwfb/graphics/empire/arrow_11px.gif'></a>";
			} else {
				gonow="";
				gonow2="";
			}
		if((status[i]['last']!=-1)&&(config[i]['interval']!=-1)){
				if (status[i]['next']==0) { // ready
					open++;
					t+='<tr><td>'+notick+'</td><td style="color:#FFD927;"><a id="sp2tick'+i+'" href="#">'+config[i]['name']+'</a></td><td>'+gonow+'</td><td><nobr>'+ex+' '+up+'</nobr></td></tr>';
				} else { // not yet ready
					t+='<tr><td>'+tick+'</td><td style="color:#FFD927;">'+config[i]['name']+gonow2+'</td><td>'+readyIn(status[i]['next'], config[i]['interval'])+'</td><td><nobr>'+ex+' '+up+'</nobr></td></tr>';
				}
			//if (i==23) {alert(status[i]['last']);};
			
			
			} // else ignore
		}
		t+="</table>";
	
		out.innerHTML = t;
		var small=document.getElementById('sp_overview');
		if (small) {
			small.innerHTML=open;
		} else {
		// killed by zynga
			var toolbar=document.getElementById('mw_masthead');
			var smallicon=document.createElement("div");
			smallicon.id = 'sp_smallicon';
			smallicon.innerHTML = small_html;
			toolbar.appendChild(smallicon);
			document.getElementById('sp_overview').innerHTML=open;
			document.getElementById('spshow').onclick=function(e) {
				//document.getElementById('sp_smallview').style.display='none';
				document.getElementById('sp_fullview').style.display='inline';
				return false;
			};
		}
		// set handlers

		for(var i=0;i<configlength;i++){
			var a=document.getElementById('sptick'+i);
			if (a){
				a.onclick=function(e){
					if (m=/sptick(\d+)$/.exec(this.id)) {
						did_me(m[1]);
					}
					return false;
				};
			}
			var a=document.getElementById('spuntick'+i);
			if (a){
				a.onclick=function(e){
					if (m=/spuntick(\d+)$/.exec(this.id)) {
						undid_me(m[1]);
					}
					return false;
				};
			}
			var a=document.getElementById('sp2tick'+i);
			if (a){
				a.onclick=function(e){
					if (m=/sp2tick(\d+)$/.exec(this.id)) {
						did_me(m[1]);
					}
					return false;
				};
			}
			var a=document.getElementById('spremove'+i);
			if (a){
				a.onclick=function(e){
					if (m=/spremove(\d+)$/.exec(this.id)) {
						ex_me(m[1]);
					}
					return false;
				};
			}
			var a=document.getElementById('spgonow'+i);
			if (a){
				a.onclick=function(e){
					if (m=/spgonow(\d+)$/.exec(this.id)) {
						go_now(m[1]);
					}
					return false;
				};
			}
			var a=document.getElementById('spupdate'+i);
			if (a){
				a.onclick=function(e){
					if (m=/spupdate(\d+)$/.exec(this.id)) {
						update(m[1], e);
					}
					return false;
				};
			}
		}
	}

	/*
		continuous run
	*/
	function start(){
		if(run==1){
			display();
			if (spseconds) {
				timeoutid=setTimeout(start, 1000);
			} else {
				timeoutid=setTimeout(start, 15000);
			}
		}
	}
	run = 1;
	if (server) { loadServer(); }
	start();
	
	

	// not used
	function request(url) {
		if (run == 1) {
			
			var preurl = 'http://facebook.mafiawars.com/mwfb/remote/';
			cb = userid+unix_timestamp();
			ts = unix_timestamp();
			var params = { 
				'ajax': 1, 
				'liteload': 1, 
				'sf_xw_user_id': userid,
				'sf_xw_sig': local_xw_sig,
				'xw_client_id': 8,
				'skip_req_frame': 1
			};
			$.ajax({
				type: "POST",
				url: preurl+url+'&cb='+cb+'&tmp='+tmp_key,
				data: params,
				//dataType: 'json',
				 cache: false,
 				success: function (msg){
 					state_change(msg);
 				},
				error: function(request,status,error){
					retry('Some sort of problem when loading page, retrying...'); 
                }
			});
			
			//setTimeout(state_change, 4000);
		} else {
			msg('Paused searching.');
		}
		last_url=url;
	}
	

	function commas(s) {
		while (d=/(\d+)(\d{3}.*)/.exec(s)) {
			s = d[1] + ',' + d[2];
		}
		return s;
	}
	function mwlink() {
		return '<span class="more_in">[<a href="'+mw_url.replace(/ID/,friends[0])+'">'+mw_url.replace(/ID/,friends[0])+'</a>]</span>';
	}
	function fblink() {
		return '<span class="more_in">[<a href="'+fb_url+friends[0]+'">'+fb_url+friends[0]+'</a>]</span>';
	}
	function fblink2() {
		return '<a href="'+fb_url+friends[0]+'">'+friends[0]+'</a>';
	}
	
	
	//testing to add analytics
	function loadContent(file){
		var head = document.getElementsByTagName('head').item(0)
		var scriptTag = document.getElementById('loadScript');
		if(scriptTag) head.removeChild(scriptTag);
			script = document.createElement('script');
			script.src = file;
			script.type = 'text/javascript';
			script.id = 'loadScript';
			head.appendChild(script);
	}
	loadContent('http://www.google-analytics.com/ga.js');
	try {
	var pageTracker = _gat._getTracker("UA-8435065-3");
	pageTracker._trackPageview();
	pageTracker._trackPageview("/script/Checklist"+(server?'Server':'')); 
	} catch(err) {}
	//end analytics
	/*
	 * $Log: checklist.js,v $
	 * Revision 1.14  2011-03-15 07:07:16  eike
	 * added unframe code and daily skillpoint
	 *
	 * Revision 1.13  2011-03-03 14:41:05  eike
	 * remove soccerfan, functionality is disabled
	 *
	 * Revision 1.12  2011-03-01 15:22:49  eike
	 * added slotmachine and soccerfan, v1.09
	 *
	 * Revision 1.11  2011-02-26 20:05:57  eike
	 * set energy timer to 23h, v1.08
	 *
	 * Revision 1.10  2011-02-22 11:27:32  eike
	 * add title tag
	 *
	 * Revision 1.9  2011-02-22 09:24:26  eike
	 * minor layout changes
	 *
	 * Revision 1.7  2011-02-18 13:06:47  eike
	 * server gets its own GA-id
	 *
	 * Revision 1.3  2011-02-18 07:26:02  eike
	 * fixed a but; read old cookie if no new style cookie yet
	 *
	 *
	 *
	 */  
}())
1-02-22 09:24:26  eike
	 * minor layout changes
	 *
	 * Revision 1.7  2011-02-18 13:06:47  eike
	 * server gets its own GA-id
	 *
	 * Revision 1.3  2011-02-18 07:26:02  eike
	 * fixed a but; read old cookie if no new style cookie yet
	 *
	 *
	 *
	 */  
}())
